# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the LICENSE file in
# the root directory of this source tree. An additional grant of patent rights
# can be found in the PATENTS file in the same directory.

import math
import torch.nn.functional as F
import torch
from torch import autograd

from fairseq import utils

from fairseq.criterions import FairseqCriterion, register_criterion


@register_criterion('story_cross_entropy_without_event_rl')
class StoryLabelSmoothedCrossEntropyCriterionWithoutEventRl(FairseqCriterion):

    def __init__(self, args, task):
        super().__init__(args, task)
        self.eps = args.label_smoothing
        self.gama = args.mixed_weight

    @staticmethod
    def add_args(parser):
        """Add criterion-specific arguments to the parser."""
        # fmt: off
        parser.add_argument('--label-smoothing', default=0., type=float, metavar='D',
                            help='epsilon for label smoothing, 0 means no label smoothing')
        parser.add_argument('--mixed-weight', default=0.1, type=float, metavar='D',
                            help='epsilon for label smoothing, 0 means no label smoothing')
        # fmt: on

    def forward(self, model, sample, scorer=None, reduce=True):
        """Compute the loss for the given sample.

        Returns a tuple with three elements:
        1) the loss
        2) the sample size, which is used as the denominator for the gradient
        3) logging outputs to display while training
        """
        with autograd.detect_anomaly():
            # mle loss for pre training
            if scorer is None:
                net_output = model(**sample['net_input'])
                loss, nll_loss = self.compute_mle_loss(model, net_output, sample, reduce=reduce)
                sample_size = sample['target'].size(0) if self.args.sentence_avg else sample['ntokens']
                logging_output = {
                    'loss': utils.item(loss.data) if reduce else loss.data,
                    'nll_loss': utils.item(nll_loss.data) if reduce else nll_loss.data,
                    'ntokens': sample['ntokens'],
                    'nsentences': sample['target'].size(0),
                    'sample_size': sample_size,
                }
            # pg loss for adv training
            else:
                # org mle loss
                net_output = model(**sample['net_input'])
                loss, nll_loss = self.compute_mle_loss(model, net_output, sample, reduce=reduce)
                sample_size = sample['target'].size(0) if self.args.sentence_avg else sample['ntokens']

                # get reward of fake example
                scorer.eval()
                with torch.no_grad():
                    # baseline reward
                    shuffle_dis_result = scorer(**sample['net_input'])
                    shuffle_avg_reward = shuffle_dis_result['neg_article_scores']
                    # average sentence reward
                    shuffle_scores = shuffle_dis_result['neg_scores']
                    shuffle_score_pad_mask = shuffle_dis_result['score_pad_mask']
                    shuffle_scores = shuffle_scores[shuffle_score_pad_mask].mean()

                    # sample reward
                    sample['net_input']['src_tokens'] = sample['net_input']['neg_src_tokens']
                    sample['tgt_prompt_mask'] = sample['neg_tgt_prompt_mask']
                    sample['target'] = sample['neg_target']

                    sample_dis_result = scorer(**sample['net_input'])
                    sample_word_reward = sample_dis_result['word_scores']
                    # average sentence reward
                    pos_scores = sample_dis_result['pos_scores']
                    pos_score_pad_mask = sample_dis_result['score_pad_mask']
                    pos_scores = pos_scores[pos_score_pad_mask].mean()

                    # final reward
                    time = sample['net_input']['src_tokens'].size(1)
                    reward = sample_word_reward - shuffle_avg_reward.unsqueeze(dim=1).expand(-1, time).contiguous().view(-1, 1)
                    # pos_scores = pos_scores - shuffle_scores

                # compute pg loss
                net_output = model(**sample['net_input'])
                pg_loss, mean_reward = self.compute_adv_loss(model, net_output, sample, reward, reduce=reduce)

                # combine two losses
                loss = (1- self.gama) * loss + self.gama * pg_loss * sample_size

                # log
                logging_output = {
                    'loss': utils.item(loss.data) if reduce else loss.data,
                    'nll_loss': utils.item(nll_loss.data) if reduce else nll_loss.data,
                    'ntokens': sample['ntokens'],
                    'nsentences': sample['target'].size(0),
                    'sample_size': sample_size,
                    'pos_scores': pos_scores.item(),
                    'neg_scores': shuffle_scores.item(),
                    'pg_loss': pg_loss.item(),
                    'mean_reward': mean_reward.item(),
                }
            return loss, sample_size, logging_output

    def compute_mle_loss(self, model, net_output, sample, reduce=True):
        lprobs = model.get_normalized_probs(net_output, log_probs=True)
        lprobs = lprobs.view(-1, lprobs.size(-1))
        target = model.get_targets(sample, net_output).contiguous().view(-1, 1)
        # non_pad_mask = target.ne(-1)

        # add prompt mask
        tgt_prompt_mask = sample['tgt_prompt_mask'].contiguous().view(-1, 1)
        non_pad_mask = tgt_prompt_mask

        nll_loss = -lprobs.gather(dim=-1, index=target)[non_pad_mask]
        smooth_loss = -lprobs.sum(dim=-1, keepdim=True)[non_pad_mask]
        if reduce:
            nll_loss = nll_loss.sum()
            smooth_loss = smooth_loss.sum()
        eps_i = self.eps / lprobs.size(-1)
        loss = (1. - self.eps) * nll_loss + eps_i * smooth_loss
        return loss, nll_loss

    def compute_adv_loss(self, model, net_output, sample, reward, reduce=True):
        lprobs = model.get_normalized_probs(net_output, log_probs=True)
        lprobs = lprobs.view(-1, lprobs.size(-1))
        target = model.get_targets(sample, net_output).contiguous().view(-1, 1)
        # non_pad_mask = target.ne(-1)

        # reward: b -> b x t -> bt x 1
        # text_lengths = sample['tgt_prompt_mask'].size(1)
        # reward = reward.unsqueeze(dim=1).expand(-1, text_lengths).contiguous().view(-1, 1)

        # add prompt mask
        tgt_prompt_mask = sample['tgt_prompt_mask'].contiguous().view(-1, 1)
        non_pad_mask = tgt_prompt_mask

        nll_loss = (-lprobs.gather(dim=-1, index=target) * reward)[non_pad_mask]
        if reduce:
            nll_loss = nll_loss.sum()
        loss = nll_loss

        # normalize to each word
        loss = loss / non_pad_mask.nonzero().size(0)

        mean_reward = reward[tgt_prompt_mask].mean()

        return loss, mean_reward

    @staticmethod
    def aggregate_logging_outputs(logging_outputs):
        """Aggregate logging outputs from data parallel training."""
        ntokens = sum(log.get('ntokens', 0) for log in logging_outputs)
        nsentences = sum(log.get('nsentences', 0) for log in logging_outputs)
        sample_size = sum(log.get('sample_size', 0) for log in logging_outputs)
        agg_output =  {
            'loss': sum(log.get('loss', 0) for log in logging_outputs) / sample_size / math.log(2),
            'nll_loss': sum(log.get('nll_loss', 0) for log in logging_outputs) / ntokens / math.log(2),
            'ntokens': ntokens,
            'nsentences': nsentences,
            'sample_size': sample_size,
        }

        if 'pos_scores' in logging_outputs[0]:
            agg_output['pos_scores'] = sum(log.get('pos_scores', 0) for log in logging_outputs) / len(logging_outputs)
            agg_output['neg_scores'] = sum(log.get('neg_scores', 0) for log in logging_outputs) / len(logging_outputs)
            agg_output['pg_loss'] = sum(log.get('pg_loss', 0) for log in logging_outputs) / len(logging_outputs)
            agg_output['mean_reward'] = sum(log.get('mean_reward', 0) for log in logging_outputs) / len(logging_outputs)

        return agg_output
